package com.ailanyin.admin.service.impl;

import com.ailanyin.admin.service.SysConfigService;
import com.ailanyin.admin.service.SysUserService;
import com.ailanyin.common.constant.UserConstants;
import com.ailanyin.common.exception.Asserts;
import com.ailanyin.common.service.RedisService;
import com.ailanyin.common.utils.EmptyUtil;
import com.ailanyin.common.utils.StringUtil;
import com.ailanyin.mapper.SysConfigMapper;
import com.ailanyin.model.SysConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:44
 */
@Service
public class SysConfigServiceImpl implements SysConfigService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisService redisService;
    @Resource
    private SysConfigMapper configMapper;

    @Value("${redis.database}")
    private String database;

    private static final String KEY = ":sys:config:";

    /**
     * 项目启动时，同步配置到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    @Override
    public List<SysConfig> selectConfigList(SysConfig config) {
        return configMapper.selectConfigList(config);
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig());
        configsList
                .stream()
                .filter(config -> EmptyUtil.isNotEmpty(config.getConfigKey()) && EmptyUtil.isNotEmpty(config.getConfigValue()))
                .forEach(this::addToRedis);
    }

    @Override
    public String selectConfigByKey(String configKey) {

        if (redisService.get(database + KEY + configKey) != null) {
            return redisService.get(database + KEY + configKey).toString();
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        SysConfig retConfig = configMapper.selectConfig(config);
        if (StringUtil.isNotNull(retConfig)) {
            addToRedis(retConfig);
            return retConfig.getConfigValue();
        }
        return StringUtil.EMPTY;
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return SysConfig 参数配置信息
     */
    @Override
    public SysConfig selectConfigById(Long configId) {
        SysConfig config = new SysConfig();
        config.setConfigId(configId);
        return configMapper.selectConfig(config);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysConfig(SysConfig config) {
        if (checkConfigKeyNotUnique(config)) {
            Asserts.fail("新增参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }

        config.setCreateBy(sysUserService.getCurrentUser().getUserName());
        config.setCreateTime(new Date());

        int row = configMapper.insertConfig(config);
        if (row > 0) {
            addToRedis(config);
        }
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyNotUnique(SysConfig config) {
        SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey());
        return StringUtil.isNotNull(info) && !info.getConfigId().equals(config.getConfigId());

    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysConfig(SysConfig config) {

        if (checkConfigKeyNotUnique(config)) {
            Asserts.fail("修改参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        int row = configMapper.updateConfig(config);
        if (row > 0) {
            addToRedis(config);
        }
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteConfigByIds(Long[] configIds) {
        for (Long configId : configIds) {
            SysConfig config = selectConfigById(configId);
            if (StringUtil.equals(UserConstants.YES, config.getConfigType())) {
                if (configId < 9) {
                    Asserts.fail("系统配置, 禁止删除！");
                }
                Asserts.fail(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            configMapper.deleteConfigById(configId);
            delFromRedis(config.getConfigKey());
        }
    }


    private void addToRedis(SysConfig config) {
        redisService.set(database + KEY + config.getConfigKey(), config.getConfigValue());
    }

    private void delFromRedis(String configKey) {
        redisService.del(database + KEY + configKey);
    }
}
